package com.sixth.docker.service.impl;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sixth.core.entity.CareOrder;
import com.sixth.core.entity.CareOrderItem;
import com.sixth.core.vo.R;
import com.sixth.docker.mapper.CareOrderItemMapper;
import com.sixth.docker.mapper.CareOrderMapper;
import com.sixth.docker.service.CareOrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.namespace.QName;
import java.math.BigDecimal;
import java.util.List;

/**
 * @program: sixth-hospital-parent
 * @description:
 * @author: 赵庆龙
 * @create: 2024-08-20 17:15
 **/
@Service
public class CareOrderItemServiceImpl implements CareOrderItemService {
    @Autowired
    private CareOrderItemMapper careOrderItemMapper;
    @Autowired
    private CareOrderMapper careOrderMapper;
    @Override
    public R<CareOrderItem> delectById(String itemId) {
        // 首先查询要删除的CareOrderItem的coId
        CareOrderItem careOrderItem = careOrderItemMapper.selectById(itemId);
        if (careOrderItem == null || !"0".equals(careOrderItem.getStatus())) {
            return R.error("删除失败：记录不存在或状态不符合要求");
        }
        String coId = careOrderItem.getCoId();

        // 删除CareOrderItem记录
        QueryWrapper<CareOrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("item_id", itemId);
        wrapper.eq("status", "0");
        int deleteCount = careOrderItemMapper.delete(wrapper);

        if (deleteCount > 0) {
            // 删除成功后，重新计算CareOrder的总金额
            QueryWrapper<CareOrderItem> remainingItemsWrapper = new QueryWrapper<>();
            remainingItemsWrapper.eq("co_id", coId);
            List<CareOrderItem> remainingItems = careOrderItemMapper.selectList(remainingItemsWrapper);

            BigDecimal newTotalAmount = remainingItems.stream()
                    .map(CareOrderItem::getAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 更新CareOrder的allAmount
            CareOrder careOrder = careOrderMapper.selectById(coId);
            if (careOrder != null) {
                careOrder.setAllAmount(newTotalAmount);
                careOrderMapper.updateById(careOrder);
            }

            return R.ok();
        } else {
            return R.error("删除失败");
        }
    }
}